﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;
using InTheHand.Net.Sockets;
using InTheHand.Net.Bluetooth;
using InTheHand.Net;
using System.IO;
using System.Collections;

namespace BluetoothLibrary
{
    public class SendIntervals
    {
        int STATIC_KOEFF = 5;
        int change = 0;
        string str;
        bool _shouldStop = false;
        byte[] Buffer = new byte[300];
        Stream stream = null;
        Random r = new Random();
        byte[] correctRequest = { 1 };
        InTheHand.Net.Sockets.BluetoothClient _bc = new InTheHand.Net.Sockets.BluetoothClient();
        int bytesRead = 0;
        Guid serviceName = new Guid("{fa87c0d0-afac-11de-8a39-0800200c9a66}");

        /// <summary>
        /// Возвращает true, если получен запрос от сервера
        /// </summary>
        public bool reqestListner()
        {
            InTheHand.Net.Sockets.BluetoothListener btListener = new BluetoothListener(serviceName);
            if (stream != null)
            {
                byte[] msgSend = { 0 };
                try
                {
                    stream.ReadTimeout = 10;
                    bytesRead = stream.Read(Buffer, 0, 44);
                    if (bytesRead.Equals(correctRequest[0]))
                    {
                        return true;
                    }
                    return false;
                }
                catch (Exception exeption)
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Возвращает поток при успешном соединении с сервером
        /// </summary>
        public Stream connect(BluetoothDeviceInfo[] deviceArray, object name)
        {
            int i = 0;
            int position = 0;
            while (!_shouldStop)
            {
                if (deviceArray[i].DeviceName == name)
                {
                    _shouldStop = true;
                    position = i;
                    _bc.Connect(new BluetoothEndPoint(deviceArray[position].DeviceAddress, serviceName));
                    stream = _bc.GetStream();
                    return stream;
                }
                else
                {
                    if (i == deviceArray.Length)
                    {
                        stream = null;
                        return stream;
                    }
                    else
                    {
                        i++;
                    }

                }

            }
            return stream;
        }

        /// <summary>
        /// Возвращает массив данных обнаруженных девайсов
        /// </summary>
        public BluetoothDeviceInfo[] discovery()
        {
            BluetoothDeviceInfo[] deviceArray = _bc.DiscoverDevices(100, true, false, true);
            return deviceArray;
        }


        /// <summary>
        /// Посылает серверу массив байтов
        /// </summary>
        public void sendData(Stream mStream, Int16[] arrayOfInterval, int currentPositionOfArray)
        {
            Byte[] data = getByteArray(arrayOfInterval, currentPositionOfArray);
            mStream.Write(data, 0, data.Length);
        }

        /// <summary>
        /// Собирает массив байтов для отправлния на смартфон
        /// </summary>
        private Byte[] getByteArray(Int16[] arrayOfInterval, int currentPositionFromArray)
        {
            bool islittleEndian = BitConverter.IsLittleEndian;
            bool notComplited = true;
            int currentPosition = 0;
            int bytePosition = 0;
            int length = currentPositionFromArray;
            Byte[] arrayToSend = new Byte[1];
            while (notComplited)
            {
                Byte[] bytes = BitConverter.GetBytes(arrayOfInterval[currentPosition]);
                if (islittleEndian)
                {
                    arrayToSend[bytePosition]= bytes[1];
                    IncreaseLength(ref arrayToSend, 1);
                    bytePosition++;
                    arrayToSend[bytePosition] = bytes[0];
                    IncreaseLength(ref arrayToSend, 1);
                    bytePosition++;
                }
                else
                {
                    arrayToSend[bytePosition] = bytes[0];
                    IncreaseLength(ref arrayToSend, 1);
                    bytePosition++;
                    arrayToSend[bytePosition] = bytes[1];
                    IncreaseLength(ref arrayToSend, 1);
                    bytePosition++;
                }
                currentPosition++;

                if (currentPosition == length)
                {
                    for (int i = 0; i < length; i++)
                    {
                        arrayOfInterval[i] = 0;
                    }
                    currentPositionFromArray = 0;
                    currentPosition = 0;
                    notComplited = false;
                    return arrayToSend;
                }
            }
            return arrayToSend;
        }
        private static void IncreaseLength(ref Byte[] arr, int delta)
        {
            Byte[] tmp = new Byte[arr.Length + delta];
            Array.Copy(arr, 0, tmp, 0, arr.Length);
            arr = tmp;
        }
    }
}
